package com.remoteapp.connection;

import java.io.IOException;

import android.os.StrictMode;

import com.remoteapp.networking.Client;
import com.remoteapp.networking.ClientReceiver;

public class ConnectionHandler extends Thread {

	/** The client that connects */
	private static Client client;

	private static ClientReceiver receiver;

	private static Thread recvThread;

	/**
	 * Connects the device with the given IP and port
	 * 
	 * @param ipAddress
	 *            The IP-Address to connect to
	 * @param port
	 *            The port to connect to
	 * @throws Exception
	 *             Is thrown when connection fails
	 */
	public static void connectClientToServer(String ipAddress, int port)
			throws Exception {

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		if (client == null) {
			if (receiver != null) {
				client = new Client(ipAddress, port, receiver);
				recvThread = new Thread(client);
				recvThread.start();

				// Wait for Thread started
				Thread.sleep(10);

				receiver.connectedToServer(client.getIPAdress());
				return;
			}

			client = new Client(ipAddress, port);
		} else {
			throw new Exception(
					"Client is already bound to another connection. Please disconnect before connecting to another connection");
		}
	}

	public static void setClientReceiver(ClientReceiver recv) {
		receiver = recv;
	}

	/**
	 * Indicates if the client is connected to a server or not
	 * 
	 * @return If the client is connected to a server or not
	 */
	public static boolean isConnected() {
		return (client != null);
	}

	/**
	 * Disconnects client from server
	 * 
	 * @throws IOException
	 *             Is thrown if disconnecting fails
	 */
	public static void disconnectClientFromServer() throws Exception {
		if (client == null) {
			return;
		}

		recvThread = null;
		Thread.sleep(10);

		client.disconnect();
		client = null;
	}

	/**
	 * Sends the given command via the client
	 * 
	 * @param command
	 *            The given command
	 * @throws IOException
	 *             Is thrown by the sendMessage method of the client
	 */
	public static void sendCommand(String command) throws IOException {
		if (client == null) {
			return;
		}

		client.sendMessage(command);
	}

}
